/*
 *  src/homework/p1.c
 *
 *  Harry Wei <harryxiyou@gmail.com> (C) 2011
 */
#include "process_control.h"

int p1(int argc, char **argv) 
{
	int i = 0;
	int j = 0;
	char ch = 0;
	int child_proc_number = MAX_CHILD_NUMBER;

	if (1 > argc) {
		child_proc_number = atoi(argv[1]);
		child_proc_number = (child_proc_number > 10) ? 10 : child_proc_number;
	}
	//Also you can use fork's return values for the child's pid ;-)
	pid_t *pid = (pid_t *)mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (NULL == pid) {
		g_message("Failed to create share mem for pid");
		exit(-1);
	}
	memset(pid, 0, MAX_CHILD_NUMBER);
	for (i = 0; i < child_proc_number; i++) {
		switch (fork()) {
		case -1:
			g_message("fork error!");
			exit(-1);
		case 0:
			pid[i] = getpid();
			g_message("%d process's pid is %d", i, pid[i]);
			while (1) {
				sleep(1);
			}
		default:
			sleep(1);
		}
	}
	for (i = 0; i < child_proc_number; i++) {
		g_message("process: %d, pid: %d", i, pid[i]);
	}
	while ('q' != (ch = getchar())) {
		getchar();
		if (isdigit(ch)) {
			int num = atoi(&ch);
			kill(pid[num], SIGTERM);
		} else {
			g_message("digital please ;)");
		}
	}
	g_message("process pid and 'q' for exit ;^)");
	kill(0, SIGTERM);
	g_message("Killed all the group processes!");
	return 0;
}
